package com.jotta.client.utility;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.view.KeyEvent;

import com.jotta.client.R;
import com.jotta.client.communicate.Configuration;
import com.jotta.client.communicate.StateOfClient;
import com.jotta.client.data.FileInfo;
import com.jotta.client.data.PictureInfo;
import com.jotta.client.data.TypeOfFile;
import com.jotta.client.file.FileManipulation;
import com.jotta.client.file.FileManipulationFactory;
import com.jotta.client.file.FileManipulationType;

public class Utility {

    private static final long K = 1024;
    private static final long M = K * K;
    private static final long G = M * K;
    private static final long T = G * K;


    public static void showFileManipulateDialog(final Context context,
                                                final FileInfo fileInfo,
                                                final String localFilePath) {

        final TypeOfFile typeOfFile = fileInfo.getTypeOfFile();
        final CharSequence[] items = createItemsForDownloadedFileDialog(typeOfFile);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(Configuration.getRes().getString(R.string.download_completed_dialog_header));
        builder.setItems(items, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int item) {
                FileManipulationType fileManipulationType = FileManipulationType.NONE;

                if (items.length == 3) {
                    if (item == 0) {
                        if (typeOfFile == TypeOfFile.PICTURE) {
                            fileManipulationType = FileManipulationType.BROWSE_PICTURES;
                        } else
                            fileManipulationType = FileManipulationType.OPEN_WITH_APPS;
                    } else if (item == 1) {
                        fileManipulationType = FileManipulationType.EMAIL;
                    }

                } else if (items.length == 2) {
                    if (item == 0) {
                        fileManipulationType = FileManipulationType.EMAIL;
                    }
                }

                FileManipulation fileManipulation = FileManipulationFactory.getFileManipulation(context, fileManipulationType, fileInfo, localFilePath);
                if (fileManipulation != null) {
                    fileManipulation.doAction();
                }

            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private static CharSequence[] createItemsForDownloadedFileDialog(
            TypeOfFile type) {
        String cancel = Configuration.getRes().getString(
                R.string.cancel_file_menu);
        String email = Configuration.getRes().getString(
                R.string.email_file_menu);
        String mediaHandle = "";
        if (type == TypeOfFile.MUSIC) {
            mediaHandle = Configuration.getRes().getString(
                    R.string.listen_music_file_menu);
        } else if (type == TypeOfFile.PICTURE) {
            mediaHandle = Configuration.getRes().getString(
                    R.string.view_picture_file_menu);
        } else if (type == TypeOfFile.PDF) {
            mediaHandle = Configuration.getRes().getString(
                    R.string.read_pdf_file_menu);
        } else if (type == TypeOfFile.VIDEO) {
            mediaHandle = Configuration.getRes().getString(
                    R.string.watch_video_file_menu);
        } else if (type != TypeOfFile.UNKNOW) {
            mediaHandle = Configuration.getRes().getString(
                    R.string.open_with_file_menu);
        }
        if (mediaHandle == "") {
            return new CharSequence[]{email, cancel};
        } else {
            return new CharSequence[]{mediaHandle, email, cancel};
        }
    }

    public static ProgressDialog getProgressDialog(Context context,
                                                   Resources res) {
        String progressBarTitle = res.getString(R.string.progress_bar_title);
        String progressBarDescription = res
                .getString(R.string.progress_bar_description);
        return ProgressDialog.show(context, progressBarTitle,
                progressBarDescription, true);
    }

    /**
     * Create progress bar
     *
     * @param context
     * @param res
     * @return
     */
    public static ProgressDialog getProgressBar(Context context, Resources res) {

        String progressBarTitle = res.getString(R.string.progress_bar_title);
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage(progressBarTitle);
        progressDialog.setCancelable(false);


        progressDialog.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (Configuration.getStateOfClient() == StateOfClient.DOWNLOADING) {
                        Configuration.setStateOfClient(StateOfClient.CANCEL_DOWNLOAD);
                    }
                }
                return true;
            }
        });

        return progressDialog;
    }

    public static Builder getAlertDialog(Context context, Resources res,
                                         String errorMessage) {

        DialogInterface.OnClickListener onClicListn = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int sumthin) {
                // do nothing it will close on its own

            }
        };

        return new AlertDialog.Builder(context)
                .setTitle(res.getString(R.string.alert_title))
                .setMessage(errorMessage)
                .setNegativeButton(res.getString(R.string.alert_close_button), onClicListn);
    }

    /**
     * Determine file type base on value in res/values/fileendings.xml.
     *
     * @param fileName : name of file
     * @return TypeOfItem
     */
    public static TypeOfFile filterFile(String fileName) {
        Resources res = Configuration.getRes();
        if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingPicture))) {
            return TypeOfFile.PICTURE;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingMusic))) {
            return TypeOfFile.MUSIC;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingVideo))) {
            return TypeOfFile.VIDEO;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingPDF))) {
            return TypeOfFile.PDF;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingPresentation))) {
            return TypeOfFile.PRESENTATION;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingRichText))) {
            return TypeOfFile.RICHTEXT;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingSpreadSheet))) {
            return TypeOfFile.SPREADSHEET;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingText))) {
            return TypeOfFile.TEXT;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingWord))) {
            return TypeOfFile.WORD;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingXML))) {
            return TypeOfFile.XML;
        } else if (checkEndsWithInStringArray(fileName,
                res.getStringArray(R.array.fileEndingZip))) {
            return TypeOfFile.ZIP;
        } else {
            return TypeOfFile.UNKNOW;
        }
    }

    public static String convertToStringRepresentation(final long value) {

        final long[] dividers = new long[]{T, G, M, K, 1};
        final String[] units = new String[]{"TB", "GB", "MB", "KB", "B"};
        try {
            if (value == 0)
                return "0 MB";
            else if (value < 0)
                return Configuration.getRes().getString(R.string.unlimited_storage);
            else {
                String result = null;
                for (int i = 0; i < dividers.length; i++) {
                    final long divider = dividers[i];
                    if (value >= divider) {
                        result = format(value, divider, units[i]);
                        break;
                    }
                }
                return result;
            }
        } catch (Exception e) {
            return "0 MB";
        }
    }

    private static String format(final long value, final long divider, final String unit) {
        final double result = divider > 1 ? (double) value / (double) divider : (double) value;
        return new DecimalFormat("#,##0.#").format(result) + " " + unit;
    }

    /**
     * Checks whether checkItsEnd ends with one of the Strings from fileEndings
     */
    private static boolean checkEndsWithInStringArray(String checkItsEnd,
                                                      String[] fileEndings) {
        for (String aEnd : fileEndings) {
            if (checkItsEnd.toLowerCase().endsWith(aEnd))
                return true;
        }
        return false;
    }

    public static String convertServer2LocalFolder(String serverPath) {
        String filePath = serverPath.replace(Configuration.INITIAL_SERVER_PATH, Configuration.INITIAL_CLIENT_PATH);
        return Environment.getExternalStorageDirectory().getAbsolutePath() + Uri.decode(filePath);

    }

    public static int getIndexOfPictureInfo(ArrayList<PictureInfo> pictureInfos, String fileName) {
        int i = 0;
        for (PictureInfo pictureInfo : pictureInfos) {
            if (pictureInfo.getTitle().equals(fileName))
                return i;
            else
                i++;
        }
        return i;
    }

    static public String encodeFolderName(String folderName) {
        return Uri.encode(folderName);
    }

    static public String decodeFolderName(String encodedFolderName) {
        return Uri.decode(encodedFolderName);
    }
}
